package com.kwshare.auth.controller;

import com.kwshare.auth.service.ILoginService;
import com.kwshare.common.core.domain.Response;
import com.kwshare.common.core.domain.auth.LoginBody;
import com.kwshare.common.core.domain.auth.LoginUser;
import com.kwshare.common.security.service.TokenService;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 认证中心
 *
 * @author yangjing
 */
@RestController
public class LoginController {

    @Resource
    private TokenService tokenService;

    @Resource
    private ILoginService loginService;

    /**
     * 登录
     *
     * @param loginBody 用户登录表单对象
     * @param httpServletRequest httpServletRequest
     * @return 结果
     */
    @PostMapping("/login")
    public Response<?> login(@RequestBody LoginBody loginBody, HttpServletRequest httpServletRequest){
        try {
            LoginUser userInfo = loginService.login(loginBody.getUsername(), loginBody.getPassword(),httpServletRequest);
            return Response.ok(tokenService.createToken(userInfo));
        }catch (Exception e){
            return Response.fail("账号或者密码错误！");
        }


    }

    /**
     * 退出登录
     *
     * @param httpServletRequest httpServletRequest
     * @return 结果
     */
    @DeleteMapping("/logout")
    public Response<?> logout(HttpServletRequest httpServletRequest){
        loginService.logout(httpServletRequest);
        return Response.ok();
    }
}
